<template>
    <div>
        <el-card>
            <div style="margin-bottom: 16px;">
                <el-button type="primary" icon="Plus">商品上架</el-button>
            </div>
            <el-form :inline="true" v-model="searchForm" style="margin-bottom: 16px;">
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.title" placeholder="商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-cascader v-model="searchForm.categoryIds" :options="categories" :props="{
                        checkStrictly: false,
                        value: 'id',
                        label: 'name',
                        children: 'children',
                        emitPath: true,
                        changeOnSelect: false
                    }" clearable placeholder="请选择商品分类" @change="handleSearch"  @clear="handleSearch" >
                    </el-cascader>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="tableData" border v-loading="loading" style="width: 100%">
                <el-table-column prop="id" label="编号" width="80" align="center" />
                <el-table-column prop="title" label="商品名称" min-width="160" />
                <el-table-column prop="mainImage" label="商品图片" width="100" align="center">
                    <template #default="scope">
                        <img v-if="scope.row.mainImage" :src="scope.row.mainImage"
                            style="width: 60px; height: 60px; object-fit: contain;" alt="商品图片" />
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="90" align="center">
                    <template #default="scope">￥{{ scope.row.price }}</template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" width="90" align="center" />
                <el-table-column prop="sales" label="销量" width="90" align="center" />
                <el-table-column prop="status" label="状态" width="90" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                            {{ scope.row.status === 1 ? '上架' : '下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="商品描述" min-width="200">
                    <template #default="scope">
                        <el-tooltip class="item" effect="dark"
                            :content="scope.row.description ? scope.row.description.replace(/<[^>]+>/g, '') : ''"
                            placement="top">
                            <span class="ellipsis-text">
                                {{ scope.row.description ? scope.row.description.replace(/<[^>]+>/g, '') : '' }}
                            </span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="350" align="center">
                    <template #default="scope">
                        <el-button size="mini">编辑</el-button>
                        <el-button size="mini" :type="scope.row.status === 1 ? 'warning' : 'success'">
                            {{ scope.row.status === 1 ? '下架' : '上架' }}
                        </el-button>
                        <el-button size="mini" type="danger">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :total="total" @current-change="handlePageChange" @size-change="handleSizeChange"
                layout="total,sizes,prev,pager,next,jumper" style="margin-top:16px" />
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
// 假设这两个接口函数已在其他文件中定义并导出
import { getProductList } from '../api/productList.js'
import { getCategoryTree } from '../api/categoryList.js'

// 响应式数据
const loading = ref(false);
const searchForm = ref({ title: '', categoryIds: [] });
const categories = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const tableData = ref<Product[]>([]);
interface SearchForm {
    title: string;
    categoryIds: number[];
}

interface Product {
    id: number;
    title: string;
    mainImage: string;
    price: number;
    stock: number;
    sales: number;
    status: 0 | 1;
    description: string;
}
// 方法定义
const fetchProductList = async () => {
    loading.value = true;
    try {
        const params = {
            title: searchForm.value.title,
            categoryId: searchForm.value.categoryIds.length > 0
                ? searchForm.value.categoryIds[searchForm.value.categoryIds.length - 1]
                : null,
            page: currentPage.value,
            pageSize: pageSize.value
        };
        const data = await getProductList(params);
        console.log(data)
        if (data.code === 0) {
            tableData.value = data.data.list || [];

            total.value = data.data.total || 0;
        } else {
            ElMessage.error(data.msg || '获取商品列表失败');
            tableData.value=[]
        }
    } catch {
        //  tableData.value=[]
        ElMessage.error("获取商品列表失败");
       
    } finally {
        loading.value = false;
    }
};

const fetchCategoryList = async () => {
    try {
        const res = await getCategoryTree()
        if (res.code === 0) {
            function cleanCategroyChildren(list) {
                if (!Array.isArray(list)) return;
                list.forEach(item => {
                    if (Array.isArray(item.children)) {
                        if (item.children.length === 0) {
                            delete item.children;
                        } else {
                            cleanCategroyChildren(item.children);
                        }
                    }
                });
            }
            cleanCategroyChildren(res.data);
            categories.value = res.data;
        }
    } catch {
        ElMessage.error("获取商品分类失败");
    } finally {
        loading.value = false;
    }
};

const handleSearch = () => {
    currentPage.value = 1;
    tableData.value = []; // 清空旧数据
    fetchProductList();
};

const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
    tableData.value = []; // 清空旧数据
    fetchProductList(); // 修复原代码中的错误，应该调用获取商品列表而不是分类列表
};

const handlePageChange = (page: number) => {
    currentPage.value = page;
    tableData.value = []; // 清空旧数据
    fetchProductList();
};

// 生命周期
onMounted(() => {
    fetchCategoryList();
    fetchProductList();
});
</script>

<style scoped>
.ellipsis-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}
</style>
